package com.shen.demo.modules.backdoor.service;

import com.shen.demo.modules.backdoor.bean.Organization;
import com.shen.demo.modules.backdoor.repository.OrganizationRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Slf4j
@Service
@Transactional
public class OrganizationService {


    @Autowired
    private OrganizationRepository repository;

    public void processOrganization(Organization org) {
//        repository.findById(org.getNo()).ifPresent(
//            existing -> updateOrganization(existing, org),
//            () -> createOrganization(org)
//        );
        Optional<Organization> optionalOrg = repository.findById(org.getNo());
        if (optionalOrg.isPresent()) {
            updateOrganization(optionalOrg.get(), org);
        } else {
            createOrganization(org);
        }
    }

    private void createOrganization(Organization org) {
        repository.save(org);
        log.info("Created organization: {}", org.getNo());
    }

    private void updateOrganization(Organization existing, Organization newData) {
        if (newData.getName() != null) existing.setName(newData.getName());
        if (newData.getStatus() != null) existing.setStatus(newData.getStatus());
        // 更新其他字段...
        
        repository.save(existing);
        log.info("Updated organization: {}", existing.getNo());
    }

    public void deleteOrganization(String no) {
        repository.deleteById(no);
        log.info("Deleted organization: {}", no);
    }
}